// Copyright 2007 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.enterprise.onebox.apps;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.logging.*;

/**
 * This servlet is intended to serve GET requests that abide by the enterprise
 * OneBox specification.  The hard work of actually finding related results is
 * delegated to other objects.
 * 
 * @author amsmith@google.com (Adam Smith)
 */
public class SimpleOneBoxServlet extends HttpServlet {
  
  private static final Logger LOGGER =
      Logger.getLogger(SimpleOneBoxServlet.class.getName());

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    String query = req.getParameter("query");
    String userName = req.getParameter("userName");
    String password = req.getParameter("password");
    String providerClass = getServletConfig().getInitParameter("providerClass");

    SimpleOneBoxProvider provider = null;
    try {
      provider = (SimpleOneBoxProvider) Class.forName(providerClass).newInstance();
    } catch (ClassNotFoundException cnfe) {
      throw new ServletException("Problem creating provider.", cnfe);
    } catch (IllegalAccessException iae) {
      throw new ServletException("Problem creating provider.", iae);
    } catch (InstantiationException ie) {
      throw new ServletException("Problem creating provider.", ie);
    }

    SimpleOneBoxResults results = provider.getResults(query, userName, password);
    if(results == null) {
      // Make sure we always return a valid response, even if it will be empty.
      results = new SimpleOneBoxResults();
    }
    
    PrintWriter out = res.getWriter();
    out.write(results.toString());
    out.close();
    
    LOGGER.info("Got " + results.getTotalResults() + " results for [" + query
        + "] as " + userName);
  }


}
